package com.auto.learning.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.auto.learning.MainActivity;
import com.auto.learning.R;
import com.auto.learning.activity.AboutusActivity;
import com.auto.learning.activity.BundingActivity;
import com.auto.learning.activity.FavorSetActivity;
import com.auto.learning.activity.LoginActivity;
import com.auto.learning.activity.MyBaseInfo;
import com.auto.learning.activity.MyMessageActivity;
import com.auto.learning.activity.ReadBookLiChengActivity;
import com.auto.learning.activity.SubscriptionActivity;
import com.auto.learning.activity.WebActivity;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.UserBaseInfo;
import com.auto.learning.bean.UserInfoBean;
import com.auto.learning.event.Handle;
import com.auto.learning.net.Cache;
import com.auto.learning.net.HttpCommonInfo;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.MyUserInfo;
import com.auto.learning.store.core.table.UserInfoTable;
import com.auto.learning.thread.pool.Pool;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.view.CircleImageView;
import com.auto.learning.view.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.sdu.didi.openapi.DiDiWebActivity;
import com.zbar.lib.CaptureActivity;

public class MenuFragment extends Fragment implements OnClickListener {
	
	private final static int GETCACHE_SUCCESS = 1;

	private SLMenuListOnItemClickListener mCallback;
	private LinearLayout linare_abous, linare_licheng, linare_favor, linare_paihang, linare_sao,linare_ggqy,linare_bind,linare_didi,linare_setting,linare_subscription;
	private RelativeLayout rel_top,rel_mymessage;
	private CircleImageView fg_me_userpic;
	private TextView tv_username,tv_grade,tv_read_num,tv_paim,tv_hhr,tv_msg_num;
	private DisplayImageOptions options;
	private ImageView image_viphead;
	
	private Handle handle =new Handle(getActivity()){
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case HttpRequestHelper.GETDATA_SUCCESS:
				ResponeResult result = (ResponeResult) msg.obj;
				UserBaseInfo baseInfo = new Gson().fromJson(result.getData(), new TypeToken<UserBaseInfo>(){}.getType());
				Cache.cacheUserInfoByJson(baseInfo.getUserId(), result.getData());
				if (baseInfo != null) {
					UserInfoBean _userInfobean = MyUserInfo.getInstance().getUserInfoBean();
					_userInfobean.setTel(baseInfo.getTel());
					_userInfobean.setIsBindTel(baseInfo.getIsBindTel());
					_userInfobean.setIsBindWeixin(baseInfo.getIsBindWeixin());
					_userInfobean.setIsBindQq(baseInfo.getIsBindQq());
					_userInfobean.setCompanyName(baseInfo.getCompanyName());
					_userInfobean.setUserGrade(baseInfo.getUserGrade());
					_userInfobean.setMsgUnread(baseInfo.getMsgUnread());
					_userInfobean.setNotifyUnread(baseInfo.getNofityUnread());
					_userInfobean.setRemindUnread(baseInfo.getRemindUnread());
					_userInfobean.setLoginName(baseInfo.getLoginName());
					_userInfobean.setFaceUrl(baseInfo.getFaceUrl());
					_userInfobean.setConfig(baseInfo.getConfig());
					_userInfobean.setVipInfo(baseInfo.getVipInfo());
					
					if (baseInfo.getMsgUnread() > 0) {
						tv_msg_num.setText(baseInfo.getMsgUnread()+"");
						tv_msg_num.setVisibility(View.VISIBLE);
						showMainViewTip(true);
					}else {
						tv_msg_num.setVisibility(View.GONE);
						showMainViewTip(false);
					}
					tv_read_num.setText(baseInfo.getBookNum()+"本");
					tv_paim.setText("前"+baseInfo.getRank());
					tv_grade.setText(baseInfo.getUserGrade());
					//合伙人，企业号
					if (baseInfo.getIsParter() == 2) {
						tv_hhr.setText(getResources().getString(R.string.text_menu_hhr));
						tv_hhr.setVisibility(View.VISIBLE);
					} else if (baseInfo.getIsParter() == 1) {
						if (TextUtils.isEmpty(baseInfo.getCompanyName())) {
							tv_hhr.setVisibility(View.GONE);
						}else {
							tv_hhr.setVisibility(View.VISIBLE);
							tv_hhr.setText(getResources().getString(R.string.text_menu_qyzxyh));
						}
					}
					if (baseInfo.getConfig() != null && baseInfo.getConfig().getIsOpenDidi() == 2) {
						linare_didi.setVisibility(View.VISIBLE);
					}else {
						linare_didi.setVisibility(View.GONE);
					}
					if (baseInfo.getIsJoinParter() == 2) {
						linare_ggqy.setVisibility(View.VISIBLE);
					}else if (baseInfo.getIsJoinParter() == 1) {
						linare_ggqy.setVisibility(View.GONE);
					}
					refreshUi();
				}
				break;
			case GETCACHE_SUCCESS:
				if (msg.obj != null) {
					UserInfoTable userinfoTable = (UserInfoTable) msg.obj;
					if (userinfoTable != null && !TextUtils.isEmpty(userinfoTable.getContent())) {
						UserBaseInfo info = new Gson().fromJson(userinfoTable.getContent(), new TypeToken<UserBaseInfo>() {}.getType());
						tv_read_num.setText(info.getBookNum() + "本");
						tv_paim.setText("前" + info.getRank());

						if (info.getIsParter() == 2) {
							tv_hhr.setText(getResources().getString(R.string.text_menu_hhr));
							tv_hhr.setVisibility(View.VISIBLE);
						} else if (info.getIsParter() == 1) {
							if (TextUtils.isEmpty(info.getCompanyName())) {tv_hhr.setVisibility(View.GONE);
							} else {
								tv_hhr.setVisibility(View.VISIBLE);
								tv_hhr.setText(getResources().getString(R.string.text_menu_qyzxyh));
							}
						}

						if (info.getIsJoinParter() == 2) {
							linare_ggqy.setVisibility(View.VISIBLE);
						} else if (info.getIsJoinParter() == 1) {
							linare_ggqy.setVisibility(View.GONE);
						}
					}
				} else {
					tv_read_num.setText("0本");
					tv_paim.setText("前--");
					tv_hhr.setVisibility(View.GONE);
					linare_ggqy.setVisibility(View.GONE);
				}
				getData();
				break;
			case HttpRequestHelper.PUBLIC_LOGIN_SUCCESS:
				ResponeResult login_result = (ResponeResult) msg.obj;
				UserInfoBean userInfoBean = new Gson().fromJson(login_result.getData(), new TypeToken<UserInfoBean>(){}.getType());
				if (userInfoBean != null) {
					SharedPreferencesUtils.setParam(getActivity(), HttpRequestHelper.USERID, userInfoBean.getUserId());
					Cache.cacheUserInfo2Local(userInfoBean);
					//登录后刷新对应账号数据
					MyUserInfo.getInstance().setUserInfoBean(userInfoBean);
					refreshUi();
					getUserBaseInfo();
					((MainActivity)getActivity()).loginSueecss();
				}
				break;
			case HttpRequestHelper.PUBLIC_LOGIN_FAIL:
				CommonMethod.makeNotice(getActivity(), msg.obj.toString());
				break;
			case 10:
				refreshUi();
				break;
			}
		};
	};
	
	private void showMainViewTip(boolean isShow){
		((MainActivity)getActivity()).showRedTip(isShow);
	}

	@Override
	public void onAttach(Activity activity) {
		try {
			mCallback = (SLMenuListOnItemClickListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + " must implement OnResolveTelsCompletedListener");
		}
		super.onAttach(activity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_menu, null);
		initImageLoader();
		initView(rootView);
		getUserBaseInfo();
		return rootView;
	}

	private void initView(View rootView) {
		image_viphead = (ImageView) rootView.findViewById(R.id.image_viphead);
		tv_hhr = (TextView) rootView.findViewById(R.id.tv_hhr);
		tv_msg_num = (TextView) rootView.findViewById(R.id.tv_msg_num);
		rel_top = (RelativeLayout) rootView.findViewById(R.id.rel_top);
		
		rel_mymessage = (RelativeLayout) rootView.findViewById(R.id.rel_mymessage);
		rel_mymessage.setOnClickListener(this);
		linare_setting = (LinearLayout) rootView.findViewById(R.id.linare_setting);
		linare_setting.setOnClickListener(this);
		linare_didi = (LinearLayout) rootView.findViewById(R.id.linare_didi);
		linare_didi.setOnClickListener(this);
		linare_ggqy = (LinearLayout) rootView.findViewById(R.id.linare_ggqy);
		linare_ggqy.setOnClickListener(this);
		linare_abous = (LinearLayout) rootView.findViewById(R.id.linare_abous);
		linare_abous.setOnClickListener(this);
		linare_licheng = (LinearLayout) rootView.findViewById(R.id.linare_licheng);
		linare_licheng.setOnClickListener(this);
		linare_favor = (LinearLayout) rootView.findViewById(R.id.linare_favor);
		linare_favor.setOnClickListener(this);
		linare_sao = (LinearLayout) rootView.findViewById(R.id.linare_sao);
		linare_sao.setOnClickListener(this);
		linare_bind = (LinearLayout) rootView.findViewById(R.id.linare_bind);
		linare_bind.setOnClickListener(this);
		linare_subscription = (LinearLayout) rootView.findViewById(R.id.linare_subscription);
		linare_subscription.setOnClickListener(this);
		fg_me_userpic = (CircleImageView) rootView.findViewById(R.id.fg_me_userpic);
		fg_me_userpic.setOnClickListener(this);
		tv_username = (TextView) rootView.findViewById(R.id.tv_username);
		tv_grade = (TextView) rootView.findViewById(R.id.tv_grade);
		tv_read_num = (TextView) rootView.findViewById(R.id.tv_read_num);
		tv_paim = (TextView) rootView.findViewById(R.id.tv_paim);
		refreshUi();
	}
	
	public void refreshUi(){
		try {
			UserInfoBean userInfoBean = MyUserInfo.getInstance().getUserInfoBean();;
			if (userInfoBean != null && userInfoBean.getUserId() == 0) {
				getLocalUserInfo();
				return;
			}
			if (userInfoBean != null && !TextUtils.isEmpty(userInfoBean.getSessionId())) {
				tv_username.setText(userInfoBean.getLoginName()+"");
				tv_grade.setText(userInfoBean.getUserGrade()+"");
				ImageLoader.getInstance().displayImage(userInfoBean.getFaceUrl(), fg_me_userpic, options);
				((MainActivity)getActivity()).refreshHead(userInfoBean.getFaceUrl());
				linare_bind.setVisibility(View.VISIBLE);
				if (userInfoBean.getVipInfo() != null && userInfoBean.getVipInfo().getVipType() == 1) {
					image_viphead.setVisibility(View.VISIBLE);
				}else {
					image_viphead.setVisibility(View.GONE);
				}
			} else {
				tv_username.setText("未登录");
				linare_ggqy.setVisibility(View.GONE);
				ImageLoader.getInstance().displayImage(userInfoBean.getFaceUrl(), fg_me_userpic, options);
//				fg_me_userpic.setImageResource(R.drawable.me_user);
				if(getActivity()!=null){
					((MainActivity)getActivity()).refreshHead("");
				}
				linare_bind.setVisibility(View.GONE);
				image_viphead.setVisibility(View.GONE);
			}
			if (userInfoBean != null) {
				userInfoBean.setMsgUnread(userInfoBean.getRemindUnread()+ userInfoBean.getNotifyUnread());
				if (userInfoBean.getRemindUnread()+ userInfoBean.getNotifyUnread() > 0) {
					tv_msg_num.setVisibility(View.VISIBLE);
					showMainViewTip(true);
					tv_msg_num.setText((userInfoBean.getRemindUnread()+ userInfoBean.getNotifyUnread()) +"");
				}else {
					tv_msg_num.setVisibility(View.GONE);
					showMainViewTip(false);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public void getLocalUserInfo(){
		Pool.getPool().execute(new Runnable() {
			
			@Override
			public void run() {
				try {
					int userId = (int)SharedPreferencesUtils.getParam(getActivity(), HttpRequestHelper.USERID, 0);
					UserInfoBean userInfoBean = Cache.getUserInfo(userId);
					if (userInfoBean != null) {
						MyUserInfo.getInstance().setUserInfoBean(userInfoBean);
					}else {
						userInfoBean = new UserInfoBean();
						userInfoBean.setUserId(userId);
						MyUserInfo.getInstance().setUserInfoBean(userInfoBean);
					}
					handle.obtainMessage(10).sendToTarget();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	/**
	 * 读书数量的变化
	 */
	public void refreshUserReadBookNumber(int bookNum){
		tv_read_num.setText(bookNum + "本");
	}

	public interface SLMenuListOnItemClickListener {

		public void selectItem(int position, String title);
	}
	
	public void openUserBaseInfo(){
		if (fg_me_userpic != null) {
			fg_me_userpic.performClick();
		}
	}
	

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.fg_me_userpic:
			Intent intent;
			if (TextUtils.isEmpty(MyUserInfo.getInstance().getUserInfoBean().getSessionId())) {
				intent = new Intent(getActivity(), LoginActivity.class);
				getActivity().startActivityForResult(intent, 100);
			}else {
				intent = new Intent(getActivity(), MyBaseInfo.class);
				getActivity().startActivityForResult(intent, 100);
			}
			break;
		case R.id.rel_mymessage:
			Intent message_intent = new Intent(getActivity(), MyMessageActivity.class);
			getActivity().startActivityForResult(message_intent, 130);
			break;
		case R.id.linare_setting:
			Intent setting_intent = new Intent(getActivity(), FavorSetActivity.class);
			getActivity().startActivityForResult(setting_intent, 100);
			break;
		case R.id.linare_didi:
			DiDiWebActivity.showDDPage(getActivity(), null);
			/*Intent ddIntent = new Intent(getActivity(), WebActivity.class);
			ddIntent.putExtra("url", "http://common.diditaxi.com.cn/general/webEntry?maptype=wgs&fromlat=39.98096907577634&fromlng=116.3000086");
			ddIntent.putExtra("showtitle", true);
			ddIntent.putExtra("title", getResources().getString(R.string.menu_ddcx));
			getActivity().startActivity(ddIntent);*/
			break;
		case R.id.linare_bind:
			Intent bindIntent = new Intent(getActivity(), BundingActivity.class);
			getActivity().startActivityForResult(bindIntent,100);
			break;
		case R.id.linare_ggqy:
			Intent mIntent = new Intent(getActivity(), WebActivity.class);
			mIntent.putExtra("url", HttpCommonInfo.MURL + "hehuoren/gdqy?userId="+SharedPreferencesUtils.getParam(getActivity(), HttpRequestHelper.USERID, 0));
			mIntent.putExtra("showtitle", true);
			mIntent.putExtra("title", getResources().getString(R.string.menu_ggqy));
			getActivity().startActivity(mIntent);
			break;
		case R.id.linare_abous:
			startActivity(AboutusActivity.class);
			break;
		case R.id.linare_sao:
			startActivity(CaptureActivity.class);
			break;
		case R.id.linare_favor:
			Intent intent2 = new Intent(getActivity(), FavorSetActivity.class);
			getActivity().startActivityForResult(intent2, 100);
			break;
		case R.id.linare_licheng:
			startActivity(ReadBookLiChengActivity.class);
			break;
		case R.id.linare_subscription:
			UserInfoBean userInfoBean = MyUserInfo.getInstance().getUserInfoBean();
			if (userInfoBean.getVipInfo() != null && userInfoBean.getVipInfo().getVipType() == 1) {
				Intent m_intent = new Intent(getActivity(), MyBaseInfo.class);
				getActivity().startActivityForResult(m_intent, 100);
			}else {
				Intent m_intent = new Intent(getActivity(), SubscriptionActivity.class);
				getActivity().startActivityForResult(m_intent, 559);
			}
			break;
		}
	}

	/**
	 * @param toClass
	 */
	private void startActivity(Class toClass) {
		Intent intent = new Intent(getActivity(), toClass);
		startActivity(intent);
//		((MainActivity)getActivity()).showMainActivity();
	}
	
	private void initImageLoader(){
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.me_user)
		.showImageForEmptyUri(R.drawable.me_user)
		.showImageOnFail(R.drawable.me_user).cacheInMemory(true)
		.cacheOnDisk(true).considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565).build();
	}
	
	private void getData(){
		String sessionId = "";
		UserInfoBean userInfoBean = MyUserInfo.getInstance().getUserInfoBean();
		if (userInfoBean != null) {
			sessionId = userInfoBean.getSessionId();
		}
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(getActivity(), HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair("sessionId", TextUtils.isEmpty(sessionId) ? "" : sessionId));
		
		params.add(new BasicNameValuePair("phoneType" , String.valueOf(1)));
		params.add(new BasicNameValuePair("phoneModel",android.os.Build.MODEL));
		params.add(new BasicNameValuePair("osVer",android.os.Build.VERSION.RELEASE));
		params.add(new BasicNameValuePair("appVer",CommonMethod.getVersionName(getActivity())));
		HttpRequestHelper.executeHttpData(getActivity(), HttpRequestHelper.USER_INFO, params, handle, HttpRequestHelper.GETDATA_SUCCESS);
	}
	
	public void getUserBaseInfo(){
		Pool.getPool().execute(new Runnable() {
			
			@Override
			public void run() {
				int userId = (int)SharedPreferencesUtils.getParam(getActivity(), HttpRequestHelper.USERID, 0);
				UserInfoBean _userInfobean = Cache.getUserInfo(userId);
				UserInfoTable info = null;
				if (_userInfobean != null) {
					info = Cache.getUserInfoByJson(userId);
					if (info != null && !TextUtils.isEmpty(info.getContent())) {
						UserBaseInfo baseInfo = new Gson().fromJson(info.getContent(), new TypeToken<UserBaseInfo>(){}.getType());
						if (baseInfo != null) {
							_userInfobean.setTel(baseInfo.getTel());
							_userInfobean.setIsBindTel(baseInfo.getIsBindTel());
							_userInfobean.setIsBindWeixin(baseInfo.getIsBindWeixin());
							_userInfobean.setIsBindQq(baseInfo.getIsBindQq());
							_userInfobean.setCompanyName(baseInfo.getCompanyName());
							_userInfobean.setUserGrade(baseInfo.getUserGrade());
							_userInfobean.setMsgUnread(baseInfo.getMsgUnread());
							_userInfobean.setNotifyUnread(baseInfo.getNofityUnread());
							_userInfobean.setRemindUnread(baseInfo.getRemindUnread());
							_userInfobean.setLoginName(baseInfo.getLoginName());
							_userInfobean.setFaceUrl(baseInfo.getFaceUrl());
							_userInfobean.setConfig(baseInfo.getConfig());
							_userInfobean.setVipInfo(baseInfo.getVipInfo());
						}
						MyUserInfo.getInstance().setUserInfoBean(_userInfobean);
					}
				}
				handle.obtainMessage(GETCACHE_SUCCESS, info).sendToTarget();
			}
		});
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		/*if (requestCode == 100 && resultCode == 203) {
			Pool.getPool().execute(new Runnable() {
				@Override
				public void run() {
					HttpRequestHelper.login2(getActivity(),data.getStringExtra("userId"), data.getStringExtra("nickName"),
							data.getStringExtra("headImgUrl"), data.getBooleanExtra("isweixin",false), handle);
				}
			});
		} else if (requestCode == 100 && resultCode == 204) {
			refreshUi();
			getUserBaseInfo();
			((MainActivity)getActivity()).loginSueecss();
		}else*/
		/*if (requestCode == 101 && resultCode == 205) {
			Log.d("onActivityResult", "onActivityResult");
			refreshUi();
		}*/
	}
	
	
}
